import socket
from simpledcpp.core.base import DCPPPart, DCPPEvent, start_new_thread
from simpledcpp.core.connections.prepare_connection import PrepareYou
import sys

class SearchListener(DCPPPart):
	""" Class for listening UDP packets (Search results """
	def __init__(self, parent, addr):
		""" Create socket and bint it to port """
		DCPPPart.__init__(self, parent)
		self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
		self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
		try:
			self.sock.bind((addr[0],int(addr[1])))
		except:
			print _('Bind to port fault.')
			sys.exit(1)
			return
		# Create main listener thread
		self._thread = start_new_thread(self._listenerThread)

	def stop(self):
		""" Stop object -> kill thread, close socket """
		try:
			self._thread.kill()
		except:
			pass
		try:
			self.sock.close()
		except:
			pass

	def _listenerThread(self):
		""" Main listener thread """
		while True:
			# Recieve datagram
			datagram = self.sock.recv(1024)
			try:
				# Check codepage
				if self.settings.get('codepage','cp1251') != 'utf8':
					datagram = self.to_utf8(datagram, self.settings.get('codepage','cp1251'))
				# Parse datagram
				l = datagram.split('/')
				f = l[0].split(' ')
				openslots = f[-1]
				f = f[:-1]
				nickname = f[1]
				f = f[2:]
				result = ""
				for i in f:
					result = result + i + ' '
				result = result.strip()
				if len(i.split('\5')) > 1:
					filenamewithpath = i.split('\5')[0]
					filesize = i.split('\5')[1]
				else:
					filenamewithpath = i
					filesize = -1
				s = l[1].split(' ')
				s = s[0].split('\5')
				allslots = s[0]
				tth = s[1].replace("TTH:", "")
				if len(result.split('\5')) > 1:
					filenamewithpath = result.split('\5')[0]
					filesize = result.split('\5')[1]
				else:
					filenamewithpath = result
					filesize = -1
				# Make event
				self.Event(DCPPEvent("ON_SEARCH_RESULT", (
								nickname,
								filenamewithpath,
								filesize,
								openslots,
								allslots,
								tth)))
			except:
				# If check exception, nothing to do.
				pass

class DownloadListener(DCPPPart):
	""" Class listen for incoming connections. """
	def __init__(self,parent, addr):
		""" Create socket and start new thread. """
		DCPPPart.__init__(self, parent)
		self._sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
		self._sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
		try:
			self._sock.bind((addr[0],int(addr[1])))
		except:
			print "Bind to port fault"
			sys.exit(1)
		self._sock.listen(5)
		# Start main listener thread
		self._thread = start_new_thread(self._listenerThread)	

	def stop(self):
		""" Kill thread and close socket. """
		try:
			self._thread.kill()
		except:
			pass
		try:
			self._sock.close()
			print _("Download listener stopped.")
		except:
			print sys.exc_info()

	def _listenerThread(self):
		""" Main listen thread. """
		try:
			while True:
				# Accept connection
				(clientsock, clientaddr) = self._sock.accept()
				try:
					# Try to start new prepare connection.
					PrepareYou(self, clientsock, clientaddr)
				except:
					pass
		except:
			# if error -> stop.
			self.stop()
		print _("WARNING: Close listener")

	
